﻿using FAQ_UI.window;
using java.io;
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using yzrilyzr.asn1;
using yzrilyzr.crypto.keys;
using yzrilyzr.FAQ.constants;
using yzrilyzr.FAQ.protocol;
using yzrilyzr.FAQ.utils;
using yzrilyzr.util;

namespace FAQ_UI
{
	/// <summary>
	/// PubkeyPage.xaml 的交互逻辑
	/// </summary>
	public partial class PubkeyPage : Page, MsgPackReceiver, INotifyPropertyChanged
	{
		private FAQID to;

		public event PropertyChangedEventHandler PropertyChanged;

		public Drawable Avatar
		{ get { return FAQUtil.getAvatar(to); } }
		public string ToName { get; set; }
		public string ToDescription { get; set; }
		public string ValidateErrText { get; set; }
		public string ValidateFAQIDErrText { get; set; }
		public string TextFAQID { get; set; }
		public string TextPubkey { get; set; }
		private DT dt = new DT();

		public PubkeyPage()
		{
			InitializeComponent();
			DataContext = this;
			FAQUtil.client.addReceiver(this);
			FAQUtil.eventBus.addReceiver(this);
			dt.getMs();
		}

		private void Page_Unloaded(object sender, RoutedEventArgs e)
		{
			//FAQUtil.client.removeReceiver(this);
			//FAQUtil.eventBus.removeReceiver(this);
		}

		protected void OnPropertyChanged(string propertyName)
		{
			if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
		}

		private void closePage(object sender, MouseButtonEventArgs e)
		{
			FAQUtil.eventBus.asyncSend(new BinMsgPack(App.CLOSE_CHAT));
		}

		private void openProfile(object sender, MouseButtonEventArgs e)
		{
			new UserProfile(to).Show();
		}

		public void receive(MsgPackTransfer mpt, MsgPack mp)
		{
			int i = mp.getCmd();
			if (i == App.OPEN_PUBKEY_SET)
			{
				to = mp.getTo();
				if (UUIDs.isNull(to)) Dispatcher.Invoke(new Action(() =>
				{
					ToName = "添加公钥";
					ToDescription = "添加公钥以添加好友";
					TextFAQID = "";
					TextPubkey = "";
					InputFAQID.IsEnabled = true;
					PubkeyASN1.Text = "";
					OthersBar.Visibility = Visibility.Collapsed;
					//deletePubkey.Visibility=Visibility.Collapsed;
					OnPropertyChanged(nameof(Avatar));
					OnPropertyChanged(nameof(ToName));
					OnPropertyChanged(nameof(ToDescription));
					OnPropertyChanged(nameof(TextFAQID));
					OnPropertyChanged(nameof(TextPubkey));
					FAQIDTextBox_TextChanged(null, null);
					TextBox_TextChanged(null, null);
				}));
				else Dispatcher.Invoke(new Action(() =>
				{
					ToName = FAQUtil.getCommNameOrName(to);
					ToDescription = FAQUtil.getDescription(to);
					TextFAQID = to.toString();
					InputFAQID.IsEnabled = false;
					OthersBar.Visibility = Visibility.Visible;
					deletePubkey.Visibility = Visibility.Visible;
					try
					{
						byte[] b64Key = FAQUtil.client.getPubKey(to);
						if (b64Key == null)
						{
							TextPubkey = "读取失败";
							PubkeyASN1.Text = "无效的ASN.1";
						}
						else
						{
							TextPubkey = Util.b64(b64Key);
							PubkeyASN1.Text = ASN1.read(new ByteArrayInputStream(b64Key)).toString();
						}
					}
					catch (Exception ex)
					{
					}
					OnPropertyChanged(nameof(Avatar));
					OnPropertyChanged(nameof(ToName));
					OnPropertyChanged(nameof(ToDescription));
					OnPropertyChanged(nameof(TextFAQID));
					OnPropertyChanged(nameof(TextPubkey));
					TextBox_TextChanged(null, null);
				}));
			}
			else if (i == C.USER_CACHE )
			{
				Dispatcher.Invoke(new Action(() =>
				{
					OnPropertyChanged(nameof(Avatar));
				}));
			}
		}

		private void TextBox_TextChanged(object sender, TextChangedEventArgs eg)
		{
			if (UUIDs.isNull(to)) return;
			string value = PubkeyB64.Text;
			if (value == null || value == "")
			{
				ValidateErrText = "请输入公钥";
				OnPropertyChanged(nameof(ValidateErrText));
				return;
			}
			try
			{
				byte[] base64 = Util.b64(value.ToString());
				string asn1value = ASN1.read(new ByteArrayInputStream(base64)).toString();
				try
				{
					PubkeyASN1.Text = asn1value;
					Byte2Key.pubkey(base64);
					ValidateErrText = "";
					OnPropertyChanged(nameof(ValidateErrText));
					if (!FAQUtil.client.hasPubKey(to))
					{
						FAQUtil.client.addE2EEKey(to, base64);
						ToName = FAQUtil.getCommNameOrName(to);
						ToDescription = FAQUtil.getDescription(to);
						OnPropertyChanged(nameof(ToName));
						OnPropertyChanged(nameof(ToDescription));
						deletePubkey.Visibility = Visibility.Visible;
						FAQUtil.eventBus.asyncSend(new BinMsgPack(ToolBar.TOOLBAR_SELECTOR).put(K.DATA, 4));
					}
					else
					{
						FAQUtil.client.addE2EEKey(to, base64);

					}
				}
				catch (Exception e)
				{
					ValidateErrText = "暂不支持此公钥";
					OnPropertyChanged(nameof(ValidateErrText));
				}
			}
			catch (Exception ee)
			{
				PubkeyASN1.Text = "无效的ASN.1";
				ValidateErrText = "无效的公钥";
				OnPropertyChanged(nameof(ValidateErrText));
			}
		}

		private void FAQIDTextBox_TextChanged(object sender, TextChangedEventArgs eg)
		{
			string value = InputFAQID.Text;
			if (value == null || value == "")
			{
				ValidateFAQIDErrText = "请输入FAQID";
				OnPropertyChanged(nameof(ValidateFAQIDErrText));
				return;
			}
			try
			{
				to = FAQID.fromString(value);
				if (UUIDs.isNull(to)) throw new NotImplementedException();
				ValidateFAQIDErrText = "";
				OnPropertyChanged(nameof(ValidateFAQIDErrText));
			}
			catch (Exception ee)
			{
				ValidateFAQIDErrText = "无效的FAQID";
				OnPropertyChanged(nameof(ValidateFAQIDErrText));
			}
		}

		private void Button_Click(object sender, RoutedEventArgs e)
		{
			string name = ((FrameworkElement)sender).Name;
			if (dt.getMs() < 1000)
			{
				MessageBox.Show("操作过快，慢一点吧", "提示", MessageBoxButton.OK);
				return;
			}
			if (name == "sendMy")
			{
				FAQUtil.client.sendMyE2EEKey(to);
			}
			else if (name == "requestOther")
			{
				FAQUtil.client.sendRequestE2EEKey(to);
			}
			else if (name == "requestServer")
			{
				FAQUtil.client.sendRequestServerE2EEKey(to);
			}
			else if (name == "deletePubkey")
			{
				if (MessageBox.Show("是否删除好友以及公钥", "删除确认", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
				{
					FAQUtil.client.removePubKey(to);
					FAQUtil.client.removeFriend(to);
					FAQUtil.eventBus.asyncSend(new BinMsgPack(ToolBar.TOOLBAR_SELECTOR).put(K.DATA, 4));
					closePage(null, null);
				}
			}
		}

		private void Page_Loaded(object sender, RoutedEventArgs e)
		{
			FAQUtil.client.addReceiver(this);
			FAQUtil.eventBus.addReceiver(this);
		}
	}
}